package com.groupbuying.sysconfig.utils;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @Description 数组处理工具类
 * @Auther Davidbieber
 * @Email davidbieber@163.com
 * @Date 2019/10/22 5:47 PM
 */
public final class ListsUtil {

    public static <E> ArrayList<E> newArrayList() {
        return new ArrayList();
    }

    /**
     * 可变参数转list
     * @param elements
     * @param <E>
     * @return
     */
    public static <E> ArrayList<E> newArrayList(E... elements) {
        checkNotNull(elements);
        int capacity = computeArrayListCapacity(elements.length);
        ArrayList<E> list = new ArrayList(capacity);
        Collections.addAll(list, elements);
        return list;
    }

    /**
     * 计算数组长度
     * @param arraySize
     * @return
     */
    public static int computeArrayListCapacity(int arraySize) {
        checkNonnegative(arraySize, "arraySize");
        return saturatedCast(5L + (long)arraySize + (long)(arraySize / 10));
    }

    /**
     * 检查键值非空
     * @param key
     * @param value
     */
    public static void checkEntryNotNull(Object key, Object value) {
        if (key == null) {
            throw new NullPointerException("null key in entry: null=" + value);
        } else if (value == null) {
            throw new NullPointerException("null value in entry: " + key + "=null");
        }
    }

    /**
     * 检查指针非空
     * @param reference
     * @param <T>
     * @return
     */
    public static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw new NullPointerException();
        } else {
            return reference;
        }
    }

    /**
     * 检查取值参数
     * @param value
     * @param name
     * @return
     */
    public static int checkNonnegative(int value, String name) {
        if (value < 0) {
            throw new IllegalArgumentException(name + " cannot be negative but was: " + value);
        } else {
            return value;
        }
    }

    /**
     * long int转换
     * @param value
     * @return
     */
    public static int saturatedCast(long value) {
        if (value > 2147483647L) {
            return 2147483647;
        } else {
            return value < -2147483648L ? -2147483648 : (int)value;
        }
    }
}
